<?php

if (! function_exists('staticize_view_path')) {
    function staticize_view_path($appendPath = null) {
        $path = 'staticize_view';

        if ($appendPath) {
            $path .= $appendPath;
        }

        return $path;
    }
}

if (! function_exists('staticize_view')) {
    function staticize_view($view = null, $data = [], $mergeData = [])
    {
        $viewObject = view($view, $data, $mergeData);

        if (!config('staticize_view.disabled')) {
            $filename = request()->path();

            if (substr($filename, -1) != '/') {
                $filename .= '.html';
            }

            if (substr($filename, -5) != '.html') {
                $filename .= 'index.html';
            }

            if (substr($filename, 0, 1) != '/') {
                $filename = '/'.$filename;
            }

            Storage::disk('local')->put(staticize_view_path($filename), $viewObject->render());
        }

        return $viewObject;
    }
}

if (! function_exists('staticize_json')) {
    function staticize_json($data = [])
    {
        if (!config('staticize_view.disabled')) {
            $filename = request()->path();

            if (substr($filename, -5) != '.json') {
                $filename .= '.json';
            }

            if (substr($filename, 0, 1) != '/') {
                $filename = '/'.$filename;
            }

            Storage::disk('local')->put(staticize_view_path($filename), json_encode($data));
        }

        return response()->json($data);
    }
}
